//index.js  
//获取应用实例  
var app = getApp();
Page({
  data: {
    status: "",
    sousuo: "",
    connectedDeviceId: "", //已连接设备uuid  
    services: "", // 连接设备的服务  
    characteristics: "", // 连接设备的状态值  
    writeServicweId: "", // 可写服务uuid  
    writeCharacteristicsId: "", //可写特征值uuid  
    readServicweId: "", // 可读服务uuid  
    readCharacteristicsId: "", //可读特征值uuid  
    notifyServicweId: "", //通知服务UUid  
    notifyCharacteristicsId: "", //通知特征值UUID  
    inputValue: "",
    characteristics1: "", // 连接设备的状态值  
    str: [],
    index: 0,
    number1: "",
    itemDetail:'',
    codes2:[]//装车条码
  },
  onLoad: function (options) {
    var that = this
    var itemDetail = JSON.parse(options.item),
      index = options.index;
    this.setData({
      itemDetail: itemDetail,
      index: index,
      goodsId: itemDetail.orders.orderGoodInfosList[that.data.index].id
    })
    console.log(index,"----------")
    console.log(itemDetail,"logs-------")
    console.log(that.data.goodsId)
    console.log(that.data.itemDetail.orders.orderStatus)
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter()
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示  
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }

  },
  // 初始化蓝牙适配器  
  lanya1: function () {
    var that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        that.setData({
          msg: "初始化蓝牙适配器成功！" + JSON.stringify(res),
        })
        //监听蓝牙适配器状态  
        wx.onBluetoothAdapterStateChange(function (res) {

          that.setData({
            sousuo: res.discovering ? "在搜索。" : "未搜索。",
            status: res.available ? "可用。" : "不可用。",
          })
          console.log(res, "--------11111")


        })
        that.lanya2()
      }
    })
  },
  // 本机蓝牙适配器状态  
  lanya2: function () {
    var that = this;
    wx.getBluetoothAdapterState({
      success: function (res) {
        that.setData({
          msg: "本机蓝牙适配器状态" + "/" + JSON.stringify(res.errMsg),
          sousuo: res.discovering ? "在搜索。" : "未搜索。",
          status: res.available ? "可用。" : "不可用。",
        })
        //监听蓝牙适配器状态  
        wx.onBluetoothAdapterStateChange(function (res) {
          that.setData({
            sousuo: res.discovering ? "在搜索。" : "未搜索。",
            status: res.available ? "可用。" : "不可用。",
          })
          console.log(res, "--------2222222222")

        })
        that.lanya3()
      }
    })
  },
  //搜索设备  
  lanya3: function () {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success: function (res) {
        that.setData({
          msg: "搜索设备" + JSON.stringify(res),
        })
        //监听蓝牙适配器状态  
        wx.onBluetoothAdapterStateChange(function (res) {
          that.setData({
            sousuo: res.discovering ? "在搜索。" : "未搜索。",
            status: res.available ? "可用。" : "不可用。",
          })
          console.log(res, "--------3333333")

        })
        that.lanya4()
      }
    })
  },
  // 获取所有已发现的设备  
  lanya4: function () {
    var that = this;
    wx.getBluetoothDevices({
      success: function (res) {
        //是否有已连接设备  
        wx.getConnectedBluetoothDevices({
          success: function (res) {
            that.setData({
              connectedDeviceId: res.deviceId
            })
          }
        })
        that.setData({
          msg: "搜索设备" + JSON.stringify(res.devices),
          devices: res.devices,
          // getBLEDeviceServices
        })
        //监听蓝牙适配器状态  
        wx.onBluetoothAdapterStateChange(function (res) {
          that.setData({
            sousuo: res.discovering ? "在搜索。" : "未搜索。",
            status: res.available ? "可用。" : "不可用。",
          })
        })
      }
    })
  },
  //停止搜索周边设备  
  lanya5: function () {
    var that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        that.setData({
          msg: "停止搜索周边设备" + "/" + JSON.stringify(res.errMsg),
          sousuo: res.discovering ? "在搜索。" : "未搜索。",
          status: res.available ? "可用。" : "不可用。",
        })
      }
    })
  },
  //连接设备  
  connectTO: function (e) {
    var that = this;
    wx.createBLEConnection({
      deviceId: e.currentTarget.id,
      success: function (res) {
        that.setData({
          connectedDeviceId: e.currentTarget.id,
          msg: "已连接" + e.currentTarget.id,
          msg1: "",
        })
        if (res.errMsg == "createBLEConnection:ok") {
          wx.showToast({
            title: '设备连接成功',
            icon: 'loading',
            duration: 2000
          });

        } else {
          wx.showToast({
            title: '设备连接失败',
            icon: 'loading',
            duration: 2000
          });
        }
      },
      fail: function () {
        wx.showToast({
          title: '设备连接失败',
          icon: 'loading',
          duration: 2000
        });
      },
      complete: function () {
        console.log("调用结束");
      }

    })
  },
  // 获取连接设备的service服务  
  lanya6: function () {
    var that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        that.setData({
          services: res.services,
          msg: JSON.stringify(res.services),
        })
        var cId = "0000fff4-0000-1000-8000-00805f9b34fb";
        wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.connectedDeviceId,
          serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
          characteristicId: "0000fff4-0000-1000-8000-00805f9b34fb",
          state: true,
          success: function (res) {
            // success
            wx.onBLECharacteristicValueChange(function (res) {
              that.getCodeByte(res.value)
            }, function (res) {
            })

            that.lanya7()
          },
          fail: function (res) {
          },
          complete: function (res) {
            // complete
          }
        })
      }
    })
  },
  //获取连接设备的所有特征值  for循环获取不到值  
  lanya7: function () {
    var that = this;
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
      deviceId: that.data.connectedDeviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
      serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {
          if (res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) {
            that.setData({
              notifyServicweId: that.data.services[0].uuid,
              notifyCharacteristicsId: res.characteristics[i].uuid,
            })
          }
          if (res.characteristics[i].properties.write) {
            that.setData({
              writeServicweId: that.data.services[0].uuid,
              writeCharacteristicsId: res.characteristics[i].uuid,
            })

          } else if (res.characteristics[i].properties.read) {
            that.setData({
              readServicweId: that.data.services[0].uuid,
              readCharacteristicsId: res.characteristics[i].uuid,
            })

          }
        }

        that.setData({
          msg: JSON.stringify(res.characteristics),
        })
      },
      fail: function () {
      },
      complete: function () {
      }
    })
    if (that.data.services.length > 0) {
      wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
        deviceId: that.data.connectedDeviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
        serviceId: "0000fff0-0000-1000-8000-00805f9b34fb",
        success: function (res) {
          for (var i = 0; i < res.characteristics.length; i++) {
            if (res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) {
              that.setData({
                notifyServicweId: that.data.services[1].uuid,
                notifyCharacteristicsId: res.characteristics[i].uuid,
              })
            }
            if (res.characteristics[i].properties.write) {
              that.setData({
                writeServicweId: that.data.services[1].uuid,
                writeCharacteristicsId: res.characteristics[i].uuid,
              })

            } else if (res.characteristics[i].properties.read) {
              that.setData({
                readServicweId: that.data.services[1].uuid,
                readCharacteristicsId: res.characteristics[i].uuid,
              })

            }
          }

          that.setData({
            msg1: JSON.stringify(res.characteristics),
          })
        },
        fail: function () {
          console.log("fail1");
        },
        complete: function () {
          console.log("complete1");
        }
      })
    }

  },
  //断开设备连接  
  lanya0: function () {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        that.setData({
          connectedDeviceId: "",
        })
      }
    })
  },
  //监听input表单  
  inputTextchange: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  lanya9: function () {
    var that = this;

  },
  onBLECharacteristicValueChange: function (cId) {
    var that = this
    wx.onBLECharacteristicValueChange(function (res) {
      that.getCodeByte(res.value)
    })

  },
  //接收消息  
  lanya10: function () {
    var that = this;

    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
    wx.onBLECharacteristicValueChange(function (res) {

      that.getCodeByte(res.value)
    })
    wx.readBLECharacteristicValue({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
      deviceId: that.data.connectedDeviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
      serviceId: that.data.readServicweId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
      characteristicId: that.data.readCharacteristicsId,
      success: function (res) {
        console.log('readBLECharacteristicValue:', res.errMsg);
      }
    })
    console.log(that.data.readServicweId);
    console.log(that.data.readCharacteristicsId);

  },
  getCodeByte: function (arrayBuffer) {
    var that = this
    var dataView = new DataView(arrayBuffer)
    for (var i = 0; i < arrayBuffer.byteLength; i++) {
      if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
        if (i > 3 && i < arrayBuffer.byteLength - 3) {
          that.data.index = i
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      } else if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01) {
        if (i > 3 && dataView.getUint8(i) != 121) {
          that.data.index = i
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      }

      else if (dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
        if (i < arrayBuffer.byteLength - 3) {
          that.data.index++
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      } else {
        if (dataView.getUint8(i) != 121) {
          that.data.index++
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      }
    }
    console.log(dataView.getUint8(0), that.data.str)
    if ((dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) || (dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A)) {
      that.getCurrentNumberString(that.data.str)
    }
  },
  getCurrentNumberString: function () {
 
    
    var that = this
    var codes2 = that.data.codes2;
    var tostring = ""

    // if (array.length > 4 && array[0] == 0x40 && array[2] == 0x53 && array[3] == 0x01 && array[that.data.index] == 0x2A) {
    tostring = String.fromCharCode.apply(String, that.data.str);
    console.log(tostring, "---------------tostring");
    that.setData({
      str: [],
      number1: tostring
    })
    
    console.log(that.data.number1)
    // that.setData({
    //   codes2: codes2//装车条码
    // })
   // console.log(that.data.codes2,"---------=============")
    if (that.data.number1){
      app.getApi.request("/api/ScanCode/Scan", { 
        orderId: that.data.itemDetail.orders.id, //关联的订单id
        goodsId: that.data.goodsId,//关联的货物id
        scanCodeType: that.data.itemDetail.orders.orderStatus,//关联的扫码类型
        code: that.data.number1,//扫码单号
        remark:''//备注
        }, "POST", (res) => {
        console.log(res,"扫码请求")
          if (res.data.responseCode == 1000) {
            if (that.data.itemDetail.orders.orderStatus == 1){
              wx.showToast({
                title: '提货扫码成功',
                icon: 'loading',
                duration: 2000
              });
            }
            if (that.data.itemDetail.orders.orderStatus == 2) {
              // codes2.push(that.data.number1)
              wx.showToast({
                title: '装车扫码成功',
                icon: 'loading',
                duration: 2000
              });
              // that.setData({
              //   codes2: codes2//装车条码
              // })
            }
            if (that.data.itemDetail.orders.orderStatus == 3) {
              wx.showToast({
                title: '收货扫码成功',
                icon: 'loading',
                duration: 2000
              });
            }
            if (that.data.itemDetail.orders.orderStatus == 4) {
              wx.showToast({
                title: '发货扫码成功',
                icon: 'loading',
                duration: 2000
              });
            }  
            if (that.data.itemDetail.orders.orderStatus == 5) {
              wx.showToast({
                title: '投递扫码成功',
                icon: 'loading',
                duration: 2000
              });
            }                       
          }else{
            wx.showToast({
              title: '扫码失败',
              icon: 'loading',
              duration: 2000
            });
          }

      }, (res) => { })
    }

    console.log("number1" + that.data.number1);

    // }
  },

  onUnload: function () {
    var that =this

    app.globalData.code2 = that.data.codes2
    console.log("999999999999------", that.data.codes2)
  },
})